﻿!function ($) {
	$.widget('codecontrib.resizable', {
		_create: function () {
			var $plugin = this;

			if ($plugin.element.attr('type') !== 'text') {
				return;
			}

			if (!$plugin.options.min) {
				$plugin.options.min = parseInt($plugin.element.css('min-width'));
			}

			if (!$plugin.options.max) {
				$plugin.options.max = parseInt($plugin.element.css('max-width'));
			}

			if ($plugin.options.min < 0
				|| isNaN($plugin.options.min)) {
				$plugin.options.min = 0;
			}

			if ($plugin.options.max < 0
				|| isNaN($plugin.options.max)) {
				$plugin.options.max = 0;
			}

			$plugin._resize();

			$plugin.element.change(function (event) {
				$plugin._resize((window.event) ? window.event.keyCode : event.which);
			})
			.keydown(function (event) {
				$plugin._resize((window.event) ? window.event.keyCode : event.which);
			});
		},
		options: {
			padding: 0,
			max: 0,
			min: 1
		},
		_resize: function (keyCode) {
			var $plugin = this;

			var text = $plugin.element.val();

			if (keyCode) {
				if (keyCode === $.ui.keyCode.UNKNOWN
					|| keyCode === $.ui.keyCode.TAB
					|| keyCode == $.ui.keyCode.SHIFT 
					|| keyCode === $.ui.keyCode.CTRL 
					|| keyCode === $.ui.keyCode.ALT
					|| keyCode === $.ui.keyCode.ESCAPE
					|| keyCode === $.ui.keyCode.LEFT
					|| keyCode === $.ui.keyCode.UP
					|| keyCode === $.ui.keyCode.RIGHT
					|| keyCode === $.ui.keyCode.DOWN) {
					return;
				}
				else if (keyCode === 8 /* Backspace */
					|| keyCode === 46 /* Delete */) {
					setTimeout(function () {
						$plugin._resize();
					}, 1);
				}
				else if (keyCode !== 127 /* Enter */) {
					text += String.fromCharCode(keyCode);
				}
			}

			var fontFamily = $plugin.element.css('font-family');
			var fontSize = $plugin.element.css('font-size');

			var $hiddenInput = $('<span/>');
			$hiddenInput.css({
				left: 0,
				'font-family': fontFamily,
				'font-size': fontSize,
				margin: '0!important',
				padding: '0 ' + $plugin.options.padding + 'px 0 0!imporant',
				position: 'absolute',
				top: 0,
				visibility: 'hidden'
			});

			$hiddenInput.html(text.replace(/ /g, '&nbsp;'));

			$('body').append($hiddenInput);

			var offsetWidth = $hiddenInput.width();

			if ($plugin.options.max > $plugin.options.padding && (offsetWidth + $plugin.options.padding) > $plugin.options.max) {
				$plugin.element.css('width', $plugin.options.max + 'px');
			}
			else if ((offsetWidth + $plugin.options.padding) <= $plugin.options.min) {
				$plugin.element.css('width', $plugin.options.min + 'px');
			}
			else {
				$plugin.element.css('width', offsetWidth + 'px');
			}

			$hiddenInput.remove();
		}
	})
} (window.jQuery)